#ifndef CENTRAL_CACHE_H_V3
#define CENTRAL_CACHE_H_V3

#include "Common.h"
#include <atomic>
#include <mutex>

using namespace std;

namespace memoryPoolV3 {
class CentralCache {
public:
    static CentralCache &getInstance() {
        static CentralCache instance;
        return instance;
    }

    void *fetchRange(size_t idx, std::size_t batchNum);
    void returnRange(void *start, size_t size, size_t index);

private:
    CentralCache() {
        for (auto &ptr : centralFreeList_)
            ptr.store(nullptr, std::memory_order_relaxed);

        for (auto &lock : locks_)
            lock.clear();
    }

    void *fetchFromPageCache(size_t size);

private:
    // 自由链表
    array<atomic<void *>, FREE_LIST_SIZE> centralFreeList_;

    // 自旋锁
    array<atomic_flag, FREE_LIST_SIZE> locks_;
};

} // namespace memoryPoolV3

#endif